import serial
import threading
import time

# 配置串口
serial_port = 'COM7'  
baud_rate = 9600      
timeout = 1           

# 打开串口
ser = serial.Serial(serial_port, baud_rate, timeout=timeout)

def read_serial():
    while True:
        if ser.in_waiting >= 13:
            packet = ser.read(13)
            if packet[0] == 0x01:
                process_packet(packet)
            else:
                print("Error: Incorrect start byte.")

def process_packet(packet):
    data1=int.from_bytes([packet[3],packet[4]],'big')
    data2=int.from_bytes([packet[5],packet[6]],'big')
    data3=int.from_bytes([packet[7],packet[8]],'big')
    data4=int.from_bytes([packet[9],packet[10]],'big')
    #print("Received valid packet:", packet.hex())
    print(f"data1={data1}data2={data2}data3={data3}data4={data4}")


# 在单独的线程中读取串口数据
read_thread = threading.Thread(target=read_serial)
read_thread.start()

# 主线程用于发送数据
try:
    while True:
        data = b'\x01\x03\x00\x69\x00\x04\x94\x15'
        ser.write(data)
        #print("Sent packet:", data.hex())
        time.sleep(1)  
except KeyboardInterrupt:
    ser.close()  
